package com.zm.xiaohashu.biz.context.interceptor;

import cn.hutool.core.util.StrUtil;
import com.zm.constant.GlobalConstants;
import com.zm.xiaohashu.biz.context.utils.LoginUserContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userIdStr = request.getHeader(GlobalConstants.USER_ID);
        if (StrUtil.isNotBlank(userIdStr)) {
            LoginUserContextHolder.setUserId(Long.parseLong(userIdStr));
        }
        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserContextHolder.remove();
    }
}
